import { reactive, computed, watch } from 'vue'
import type { PropertyPanelProps, ServiceConfig } from '../types'
import Modeling from 'bpmn-js/lib/features/modeling/Modeling.js'

export function useServiceConfig(props: PropertyPanelProps) {
  const serviceConfig = reactive<ServiceConfig>({
    implementationType: 'class',
    implementation: '',
    async: false,
  })

  const showServiceConfig = computed(() => {
    const type = props.currentElement?.type || ''
    return type === 'bpmn:ServiceTask'
  })

  const getImplementationPlaceholder = computed(() => {
    switch (serviceConfig.implementationType) {
      case 'class':
        return '请输入Java类名'
      case 'expression':
        return '请输入表达式'
      case 'delegateExpression':
        return '请输入代理表达式'
      default:
        return '请输入实现值'
    }
  })

  const handleServiceChange = () => {
    if (!props.currentElement || !props.modeler) return

    const modeling = props.modeler.get('modeling') as Modeling
    modeling.updateProperties(props.currentElement, {
      implementation: serviceConfig.implementation,
      async: serviceConfig.async,
    })
  }

  // 监听当前元素变化，更新配置
  watch(
    () => props.currentElement,
    (element) => {
      if (element && showServiceConfig.value) {
        const businessObject = element.businessObject
        serviceConfig.implementation = businessObject.implementation || ''
        serviceConfig.async = businessObject.async || false
        serviceConfig.implementationType = businessObject.class
          ? 'class'
          : businessObject.expression
            ? 'expression'
            : 'delegateExpression'
      } else {
        serviceConfig.implementation = ''
        serviceConfig.async = false
        serviceConfig.implementationType = 'class'
      }
    },
    { immediate: true },
  )

  return {
    serviceConfig,
    showServiceConfig,
    handleServiceChange,
    getImplementationPlaceholder,
  }
}
